package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-11 22:23
 **/
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private DictFeignClient dictFeignClient;


    @Autowired
    protected HospitalRepository hospitalRepository;

    //根据医院名称获取医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {

        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    //根据查询数据获取列表
    @Override
    public List<Hospital> selectHospQuery(HospitalQueryVo hospitalQueryVo) {
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Example<Hospital> example = Example.of(hospital, matcher);

        List<Hospital> hospitals = hospitalRepository.findAll(example);

        hospitals.stream().forEach(item -> {
            this.packHospital(item);
        });
        return hospitals;
    }

    //医院预约挂号详情
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.packHospital(hospitalRepository.findHospitalByHoscode(hoscode));

        //医院基本信息（包含医院等级）
        result.put("hospital", hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    //获取医院详情
    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        //医院基本信息（包含医院等级）
        result.put("hospital", hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    //获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.findHospNameByHoscode(hoscode);

        return hospital.getHosname();
    }

    @Override
    public void updateStatus(String id, String status) {
        if ("1".equals(status) || "0".equals(status)) {
            Hospital hospital = hospitalRepository.findById(id.toString()).get();

            hospital.setStatus(Integer.parseInt(status));

            hospitalRepository.save(hospital);
        }


    }

    @Override
    public void saveHospital(Map<String, Object> hospitalMap) {
        // 一般map都是通过json形式的互相转换进行存储
        String hospitalJson = JSONObject.toJSONString(hospitalMap);
        Hospital hospital = JSONObject.parseObject(hospitalJson, Hospital.class);

        // 因为医院中的编号是唯一的,所以当其他医院来调用咱们接口的时候我们需要判断是否已存在
        // 如果已存在  更新数据
        // 如果不存在  添加数据
        Hospital hospitalMG = hospitalRepository.findHospitalByHoscode(hospital.getHoscode());

        if (hospitalMG != null) {
            // 说明已存在，我们需要更新数据 更新需要id值
            hospital.setId(hospitalMG.getId());

            // 当前更新的时间
            hospital.setUpdateTime(new Date());
            hospital.setStatus(0);
            // 第一次插入的时间
            hospital.setCreateTime(hospitalMG.getCreateTime());
            hospitalRepository.save(hospital);
        } else {
            // 当前更新的时间
            hospital.setUpdateTime(new Date());
            // 第一次插入的时间
            hospital.setCreateTime(new Date());
            hospital.setStatus(0);

            hospitalRepository.save(hospital);
        }


    }

    @Override
    public Hospital findHospitalByHoscode(Object hoscode) {
        Hospital byHoscode = hospitalRepository.findHospitalByHoscode((String) hoscode);
        return byHoscode;
    }

    // 首先查询所有的数据index
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        // 首先是排序
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        // 分页
        PageRequest pageRequest = PageRequest.of(page - 1, limit, sort);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        // 数据处理
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        // 模糊查询
        Example<Hospital> example = Example.of(hospital, matcher);
        // 最终查询数据
        Page<Hospital> page1 = hospitalRepository.findAll(example, pageRequest);

        List<Hospital> hospitalList = page1.getContent();

        // 然后循环遍历进行数据处理
        hospitalList.stream().forEach(item -> {
            // 进行数据传输处理
            this.packHospital(item);
        });
        return page1;
    }

    private Hospital packHospital(Hospital hospital) {
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }
}
